<?php

namespace IYUU\sdk\CoolQ\Domain;

use Exception;
use IYUU\sdk\CoolQ\Context;
use MessageModel;
use think\facade\Db;
use function IYUU\sdk\CoolQ\getContext;

/**
 * 消息加工处理
 * - 无状态静态类
 * Class Message
 * @package IYUU\sdk\CoolQ\Domain
 */
class Message
{
    /**
     * 把消息写入数据库
     * @param Context $context
     */
    public static function save(Context $context)
    {
        try {
            $event = $context->get();
            if (isset($event['post_type']) && isset($event['self_id']) && (isset($event['group_id']) || isset($event['user_id']))) {
                // 1.查询机器人QQ {bot_key}
                $self_id = $event['self_id'];
                $bot_key = 1;

                // 2.格式化数据
                $MessageModel = new MessageModel();
                $field = $MessageModel->getTableField();
                unset($field['id']);    // id字段不允许写入
                $db_data = [
                    'bot_key' => $bot_key
                ];
                // 3.1循环赋值 $db_data
                foreach ($field as $key => $type) {
                    if (isset($event[$key])) {
                        if ($event[$key]) {
                            switch ($type) {
                                case 'int':
                                    $db_data[$key] = intval($event[$key]);
                                    break;
                                case 'string':
                                    $db_data[$key] = strval($event[$key]);
                                    break;
                                case 'array':
                                    $db_data[$key] = json_encode($event[$key], JSON_UNESCAPED_UNICODE);
                                    break;
                                default:
                                    break;
                            }
                        }
                        // 3.2移除存在的键
                        unset($event[$key]);
                    }
                }
                // 3.3剩余的键放入ext_data字段
                if (!empty($event)) {
                    unset($event['anonymous'], $event['self_id']);
                    $db_data['ext_data'] = json_encode($event, JSON_UNESCAPED_UNICODE);
                }

                // 4.写入数据库()
                MessageModel::create($db_data);
            }
        } catch (Exception $ex) {
            file_put_contents(runtime_path() . '/error_saveMessage.log', p(getContext()->get(), false), FILE_APPEND);
            file_put_contents(runtime_path() . '/error_saveMessage.log', p($ex->getMessage(), false), FILE_APPEND);
        }
    }

    /**
     * 清理消息存放表
     * @param bool $type true清空消息表，false删除30天前数据
     * @return string
     */
    public static function clear(bool $type = false): string
    {
        if ($type) {
            Db::query("TRUNCATE `cq_message`");
        } else {
            // 清理30天前的消息
            $where = date("Y-m-d H:i:s", time() - 2592000);
            MessageModel::where('created', '<', $where)->delete();
            //Db::name('cq_message')->where('created', '<', $where)->delete();
        }
        return '消息数据表cq_message，清理成功。';
    }
}
